package com.csdj.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csdj.user.common.WebResult;
import com.csdj.user.entity.ErWeiMa;
import com.csdj.user.entity.TUsers;
import com.csdj.user.service.TUsersService;
import com.csdj.user.utils.HttpClientUtil;
import com.csdj.user.utils.QRCodeUtil;
import com.csdj.user.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author wenjun
 * @since 2022-03-03
 */
@RestController
@RequestMapping("/t-users")
public class TUsersController {
    private String appid="wx003d300f700e0aae";
    private String secret="04192245c28d345174ac5e99bb41170b";
    private String url="http://452881d2q5.qicp.vip/t-users/code";
    @Autowired
    private TUsersService tUsersService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 生成登录二维码  一个小时的生效时间
     * @return 二维码路径
     */
    @GetMapping("/shengcheng")
    public WebResult shengChengErWeiMa(){
        String id=RandomUtil.getUUID(30);
        String random=RandomUtil.getUUID(8);
        QRCodeUtil.zxingCodeCreate("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+url+"&response_type=code&scope=snsapi_userinfo&state="+random+"&connect_redirect=1#wechat_redirect\"","D:/"+id+".jpg");
        ErWeiMa erWeiMa=new ErWeiMa();
        erWeiMa.setEwmUrl("http://452881d2q5.qicp.vip/img/"+id+".jpg");
        erWeiMa.setRandom(random);
        erWeiMa.setState(false);
        redisTemplate.opsForValue().set("EWM"+random,erWeiMa,3600);
        return new WebResult(0,erWeiMa);
    }

    /**
     * 连接微信公众号
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/wx")
    public String domainCheck(@RequestParam("signature")String signature,
                              @RequestParam("timestamp")Long timestamp,
                              @RequestParam("nonce")String nonce,
                              @RequestParam("echostr")String echostr){
        System.out.println(signature+","+timestamp+","+nonce+","+echostr);
        return echostr;
    }

    /**
     * 获取code
     * @param state
     * @return code
     */
    @GetMapping("/code")
    public void code(@RequestParam("code")String code,@RequestParam("state")String state){
        String openId=openid(code);
        QueryWrapper<TUsers> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(TUsers::getOpenid,openId);
        TUsers tUsers=tUsersService.getOne(queryWrapper);
        String token=getasstoken();
        String userInfo=getUserInfo(openId,token);
        System.out.println(userInfo);
        if(tUsers==null){
            System.out.println("账号未注册微信，已经为您自动注册！（默认密码123456）");
//            tUsers.setName(getJsonValueByKey(userInfo,"nickname"));
//            tUsers.setPhoto(getJsonValueByKey(userInfo,"headimgurl").replaceAll("\\\\",""));
            tUsers.setOpenid(openId);
            tUsers.setUserid(RandomUtil.getUUID(6));
            tUsers.setPassword("123456");
            tUsersService.save(tUsers);
        }
        System.out.println("登录成功");
        ErWeiMa erWeiMa=(ErWeiMa)redisTemplate.opsForValue().get("EWM"+state);
        erWeiMa.setState(true);
        redisTemplate.opsForValue().set("EWM"+state,erWeiMa,3600);
        redisTemplate.opsForValue().set("user"+state,tUsers,3600);
    }
    /**
     * 获取登录状态
     * @param state
     * @return code
     */
    @GetMapping("/state")
    public WebResult state(@RequestParam("state")String state){
        ErWeiMa erWeiMa=(ErWeiMa)redisTemplate.opsForValue().get("EWM"+state);
        if(erWeiMa.getState()==true){
            TUsers tUsers=(TUsers)redisTemplate.opsForValue().get("EWM"+state);
            return new WebResult(0,tUsers);
        }
        return new WebResult(1);
    }
    /**
     * 获得openid
     * @param
     * @return openid
     */
    public String openid(String code){
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String json=HttpClientUtil.doGet(url);
        return getJsonValueByKey(json,"openid");
    }

    /**
     * 获得用户信息
     * @param openId
     * @param token
     * @return
     */
    public  String getUserInfo(String openId,String token){
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openId;
        return  HttpClientUtil.doGet(url);
    }

    /**
     * 获得asstoken
     * @return
     */
    public String  getasstoken(){
        String strUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx003d300f700e0aae&secret=04192245c28d345174ac5e99bb41170b";
        String access_token=HttpClientUtil.doGet(strUrl);
        return getJsonValueByKey(access_token,"access_token");
    }
    /**
     * 把提取网页json格式
     * @param jsonStr
     * @param key
     * @return
     */
    public  String getJsonValueByKey(String jsonStr, String key) {
        // 此处引入的是 com.alibaba.fastjson.JSONObject; 对象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        // 获取到 key 对应的值
        return jsonObject.getString(key);
    }
}
